#include "netdisk.h"

int login(int ntfd, char *uname)
{
    int uerror = 2;
    int perror1 = 1;
    int right = 0;
    char username[256] = {0};
    char password[256] = {0};
    char salt_value[128];
    char MD5_pd_local[256];
    char *MD5_pd_getting;
    int times = 4;

    int name_length = 0;
    int pswd_length = 0;
    /**************************************************************/
    // 用户名 times--;
    /**************************************************************/
    while (1)
    {

        bzero(username, sizeof(username));
        bzero(password, sizeof(password));
        if (times == 0) // 多次密码错误退出
        {
            return -1;
        }
        recvn(ntfd, &name_length, sizeof(int));
        recvn(ntfd, username, name_length);
        recvn(ntfd, &pswd_length, sizeof(int));
        recvn(ntfd, password, pswd_length);
        
        printf("输入的用户名为：%s\n", username);
        printf("输入的密码为：%s\n", password);
        //-验证用户是否存在
        struct spwd *pswd;
        pswd = getspnam(username);
        if (pswd == NULL)
        {
            send(ntfd, &uerror, sizeof(int), 0);
            continue;
        }
        strcpy(uname, username);
        /**************************************************************/
        // 密码
        /**************************************************************/

        // 验证密码
        //-获取盐值
        strcpy(MD5_pd_local, pswd->sp_pwdp);
        int first_money, last_money;
        bool first_bool = 0;
        for (int i = 0; i < strlen(MD5_pd_local); i++)
        {
            if (MD5_pd_local[i] == '$' && first_bool == 0)
            {
                first_money = i;
                first_bool = 1;
            }
            if (MD5_pd_local[i] == '$' && first_bool == 1)
            {
                last_money = i;
            }
        }

        for (int i = first_money; i <= last_money; i++)
        {
            salt_value[i - first_money] = MD5_pd_local[i];
        }
        //-验证密码
        MD5_pd_getting = crypt(password, salt_value);
        if (strcmp(MD5_pd_getting, MD5_pd_local) == 0) // 密码正确
        {
            send(ntfd, &right, sizeof(int), 0);
            return 0;
        }
        else // 密码错误
        {

            send(ntfd, &perror1, sizeof(int), 0);
            times--;
            continue;
        }
    }
    return -1;
}
